<?php

namespace app\common\util;

class SshConnet
{
    /**
     * 执行SSH命令
     *
     * 使用方式
     * use app\common\util\SshConnet;
     * SshConnet::connectServer('cmd')
     *
     * @param string $cmd 地址
     * @param string $is_curr_rt 默认阻塞会返回结果，不阻塞会返回空(速度快，后台执行)
     * @return msg
     */
    public static function connectServer($cmd, $is_curr_rt = true)
    {
        $host = config('sshconfig.host');
        $pass = config('sshconfig.password');
        $connection = ssh2_connect($host, 22);
        if (!ssh2_auth_password($connection, 'root', $pass)) {
            return ['code' => 500, 'msg' => 'SSH连接失败！'];
        }
        $ret = ssh2_exec($connection, $cmd);
        stream_set_blocking($ret, $is_curr_rt);

        $res = stream_get_contents($ret);

        // ssh2_disconnect($connection);

        return ['code' => 200, 'msg' => '执行成功！', 'output' => $res];
    }
    public static function excssh($cmd, $is_curr_rt = true)
    {
        $output = array();
        $returnValue = 0;
        exec($cmd, $output, $returnValue);

// 输出脚本的执行结果
//        foreach ($output as $line) {
//            echo "$line\n";
//        }
        // ssh2_disconnect($connection);

        return ['code' => 200, 'msg' => '执行成功！', 'output' => $returnValue];
    }
}
